package com.epro.dx.activity;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.SystemClock;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.Display;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import com.baifendian.mobile.BfdAgent;
import com.epro.dx.R;
import com.epro.dx.listenner.CustomAsyncTaskListener;
import com.epro.dx.listenner.MyAsyncTaskListenner;
import com.epro.dx.listenner.OnLoginSuccessedListenner;
import com.epro.dx.task.GetCountryCodeTask;
import com.epro.dx.service.JobHandlerService;
import com.epro.dx.service.SurvivalService;
import com.epro.dx.task.GetIsNotReadAsyncTask;
import com.epro.dx.task.GetOneKeyFilterSettingsAsyncTask;
import com.epro.dx.task.GetTopCategoryAsyncTask;
import com.epro.dx.task.GetTrackConfigTask;
import com.epro.dx.util.ActivityUtil;
import com.epro.dx.util.AsyncTaskUtil;
import com.epro.dx.util.DiskLruCache;
import com.epro.dx.util.DiskLruCache.Snapshot;
import com.epro.dx.util.LoginUtilTask;
import com.umeng.analytics.MobclickAgent;
import com.weipu.common.constants.Constant;
import com.weipu.common.facade.exception.DxException;
import com.weipu.common.facade.factory.ProviderFactory;
import com.weipu.common.facade.model.PushSettingsModel;
import com.weipu.common.subject.MessageSubjectImpl;
import com.weipu.common.util.Common;
import com.weipu.common.util.Logger;
import com.weipu.common.util.NotificationsUtils;
import com.weipu.common.util.StringUtil;
import com.weipu.common.util.utils.JsonFormat;
import com.weipu.common.util.utils.SPUtils;
import cn.jpush.android.api.JPushInterface;

/**
 * 启动页面
 *
 * @author hjd008
 * @version [版本号, 2014-12-12]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public class StartUpActivity extends BaseFragmentActivity{
    private static final String TAG = "StartUpActivity";

    private static final String[] SD_PERMISSION = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,};

    private static final int SD_PERMISSION_REQUEST_CODE = 100;

    private ImageView bgImageview;

    private ImageView adImageView;

    private Button startBtn;

    private DiskLruCache mDiskCache;

    private Handler handler = new Handler();

    private Bitmap adPicBitmap;
    private SPUtils spUtils;


    public void onCreate(Bundle savedInstanceState) { // 不显示标题
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);

        Logger.e(Constant.TAG.TAG_TEST  + " customerID= " +ActivityUtil.getCustomerID());
        //开启保活服务
        startService(new Intent(this, SurvivalService.class));

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            startService(new Intent(this, JobHandlerService.class));
        }

        ActivityUtil.setStatusColor(this, 0, null);
        // //Testin 崩溃大师
        // TestinAgent.init(this);
        setContentView(R.layout.activity_startup);
        // 禁止默认的页面统计方式，这样将不会再自动统计Activity。
        MobclickAgent.openActivityDurationTrack(false);
        // 发送策略
        MobclickAgent.updateOnlineConfig(this);

        intView();
//		setDiskCache();
        // 同过子线程启动页跳转到主页
        Logger.i(TAG, System.currentTimeMillis() + "");
        LoginUtilTask logintask = new LoginUtilTask(
                new OnLoginSuccessedListenner() {

                    @Override
                    public void onLoginSuccesed() {
                        //登录成功，与极光推送绑定关系
                        String registrationID = JPushInterface.getRegistrationID(StartUpActivity.this);
//						Log.d(TAG, "loginfinish>registrationID:"+registrationID);
                        Long customerID = ActivityUtil.getCustomerID();
                        if (!TextUtils.isEmpty(registrationID)) {
                            //TODO 没有设置分组
                            setJPushAlias("" + customerID, null);
                        }
                        //百分点推荐用户添加
                        if (ActivityUtil.isLogin(getApplicationContext())) {
                            BfdAgent.onAddUser(getApplicationContext(), getCustomerID());
                        }
                        //获取一键过滤设置信息
                        getOnekeyFilter();
                        //获取用户是否有未读消息
                        AsyncTaskUtil.executeTask(new GetIsNotReadAsyncTask(new MyAsyncTaskListenner() {

                            @Override
                            public void onPreTask() {
                                // TODO Auto-generated method stub

                            }

                            @Override
                            public void onPostTask(String result, Object obj) {
                                boolean isNotRead = (Boolean) obj;
                                MessageSubjectImpl.getMessageSubjectImplInstance().notice(isNotRead ? 1 : 0, -1);
                            }
                        }));
                    }

                    @Override
                    public void onLoginFailed() {

                    }
                }, StartUpActivity.this, false);
//		AsyncTaskUtil.executeTask(new GetAdPicture());
//		SystemClock.sleep(1000);
		AsyncTaskUtil.executeTask(logintask);
		AsyncTaskUtil.executeTask(new GetCountryCodeTask());
		//获取一级分类
		AsyncTaskUtil.executeTask(new GetTopCategoryAsyncTask(StartUpActivity.this, null));
		handler.postDelayed(jumpRunnable, 3000);
		Logger.i(TAG, System.currentTimeMillis() + "");

        spUtils = new SPUtils(getResources().getString(R.string.app_name_en));
        //检查是否有SD卡的读取权限，如果没有则申请权限
        checkPermission();
    }

//    private void getPushConfig() {
//        try {
//            new GetTrackConfigTask(new CustomAsyncTaskListener<PushSettingsModel.DataBean>() {
//                @Override
//                public void onPostExecute(PushSettingsModel.DataBean pushSettingsModel) {
//                    if (pushSettingsModel != null) {
//                        boolean isPush = pushSettingsModel.isIsPush();
//                        Logger.e(Constant.TAG.TAG_TEST + "  获取是否推送的数据为： " + isPush);
//                        StringUtil.saveConfig("IsPush", isPush + "");
//                    }else {
//                        Logger.e(Constant.TAG.TAG_TEST + "  获取是否推送的数据为：null " );
//
//                    }
//                }
//
//            }).execute();
//        } catch (Exception e) {
//            Logger.e(Constant.TAG.TAG_TEST + "  获取是否推送的数据为： 崩溃" );
//            e.printStackTrace();
//        }
//    }

    /**
     * 动态申请权限
     */
    private void checkPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED
                    || ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED) {
                //请求权限
                requestPermission();
            }
        }
    }

    private void requestPermission() {
        ActivityCompat.requestPermissions(this, SD_PERMISSION, SD_PERMISSION_REQUEST_CODE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == SD_PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0) {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED || grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                    //此时，设备就有了sd卡的读取权限
                    spUtils.put(Constant.Global.HAS_SD_PERMISSION, true);
                } else {
                    //sd卡权限申请失败
                    spUtils.put(Constant.Global.HAS_SD_PERMISSION, false);
                }
            }
        }
    }

    /**
     * @创建：Tony 2016-4-5下午4:45:16
     * @描述：获取一键过滤设置信息
     */
    private void getOnekeyFilter() {
        AsyncTaskUtil.executeTask(new GetOneKeyFilterSettingsAsyncTask(StartUpActivity.this, null));
    }

    @Override
    protected void onResume() {
        JPushInterface.onResume(StartUpActivity.this);
        super.onResume();
    }

    @Override
    protected void onPause() {
        JPushInterface.onPause(StartUpActivity.this);
        super.onPause();
    }

    private void intView() {
        bgImageview = (ImageView) findViewById(R.id.init_imagview);
        adImageView = (ImageView) findViewById(R.id.ad_imagview);
        startBtn = (Button) findViewById(R.id.start_jump);
        startBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                handler.removeCallbacks(jumpRunnable);
                jumpActivity();
            }
        });
    }

    /**
     * 获取广告图片
     *
     * @author hf
     */

    protected class GetAdPicture extends AsyncTask<Void, Void, String> {

        private String picUrl;

        private boolean isCache;

        private int screenWidth;

        private int screenHeight;

        @Override
        protected void onPreExecute() {
            // DisplayMetrics dm = new DisplayMetrics();
            // getWindowManager().getDefaultDisplay().getMetrics(dm);
            // screenWidth=(int) (dm.widthPixels*dm.density);
            // screenHeight=(int) (dm.heightPixels*dm.density);
            WindowManager windowManager = getWindowManager();
            Display display = windowManager.getDefaultDisplay();
            screenWidth = display.getWidth();
            screenHeight = display.getHeight();
            Logger.i("FFF", screenWidth + "  gg  " + screenHeight);
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(Void... params) {
            String[] picUrls = null;
            try {
                picUrls = ProviderFactory.createAdPromotionServiceProvider()
                        .GetStartImage(screenWidth, screenHeight, "en_us");

            } catch (DxException e) {
                return e.getErrCode();
            } catch (Exception e) {
                return "exception";
            }

            // picUrl="http://p1.gexing.com/qqpifu/20120915/2108/50547de23ef59.jpg";
            // picUrl="http://img.dxcdn.com/productimages/sku_415740_1.jpg";
            if (null != picUrls && picUrls.length > 0) {
                picUrl = picUrls[0];
                if (null == picUrl || "".equals(picUrls)
                        || !picUrl.contains("http:")) {
                    return "exception";
                }
            } else {
                return "exception";
            }
            FileDescriptor fileDescriptor = null;
            FileInputStream fileInputStream = null;
            Snapshot snapShot = null;
            try {
                // 生成图片URL对应的key
                final String key = Common.hashKeyForDisk(picUrl);
                // 查找key对应的缓存
                snapShot = mDiskCache.get(key);
//				Log.i(TAG, "diskCache SnapShot: " + snapShot);
                if (null != snapShot) {
                    isCache = true;
                }
                if (snapShot == null) {
                    // 如果没有找到对应的缓存，则准备从网络上请求数据，并写入缓存
                    DiskLruCache.Editor editor = mDiskCache.edit(key);
                    if (editor != null) {
                        OutputStream outputStream = editor.newOutputStream(0);
                        if (downloadUrlToStream(picUrl, outputStream)) {
                            editor.commit();
                        } else {
                            editor.abort();
                        }
                    }
                    // 缓存被写入后，再次查找key对应的缓存
                    snapShot = mDiskCache.get(key);
                }
                if (snapShot != null) {
                    fileInputStream = (FileInputStream) snapShot
                            .getInputStream(0);
                    fileDescriptor = fileInputStream.getFD();
                }
                // 将缓存数据解析成Bitmap对象
                Bitmap bitmap = null;
                if (fileDescriptor != null) {
                    bitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor);
                }
                adPicBitmap = bitmap;
                if (!isCache) {
                    fluchCache();
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (fileDescriptor == null && fileInputStream != null) {
                    try {
                        fileInputStream.close();
                    } catch (IOException e) {
                    }
                }
            }
            if (null != adPicBitmap && isCache) {
                SystemClock.sleep(2000);
                return "0";
            }
            return "0";
        }

        @Override
        protected void onPostExecute(String result) {
            if (!isFinishing()) {
                if ("0".equals(result) && null != adPicBitmap) {
                    startBtn.setVisibility(View.VISIBLE);
                    bgImageview.setVisibility(View.GONE);
                    adImageView.setVisibility(View.VISIBLE);
                    adImageView.setImageBitmap(adPicBitmap);
                    handler.removeCallbacks(jumpRunnable);
                    handler.postDelayed(jumpRunnable, 3000);

                } else {
                    jumpActivity();
                }
            }

        }

    }

    private Runnable jumpRunnable = new Runnable() {

        @Override
        public void run() {
            jumpActivity();
        }

    };

    private void jumpActivity() {
        // -----------------------修改：首次加载先展示新特性------------------------
        // //判断是否展示过新特性
        //获取以前保存的版本号
        boolean hasShowed = false;
        String oldVersionCode = StringUtil.getConfig("VersionCode", "");
        if (!TextUtils.isEmpty(oldVersionCode)) {
            PackageManager manager = StartUpActivity.this.getPackageManager();
            String versionCode = null;
            try {
                PackageInfo packageInfo = manager.getPackageInfo(StartUpActivity.this.getPackageName(), 0);
                versionCode = packageInfo.versionCode + "";
            } catch (NameNotFoundException e) {
                versionCode = "0.1";
            }
            if (oldVersionCode.equals(versionCode)) {
                hasShowed = true;
            }
        }
//		SharedPreferences sharedPreferences = getSharedPreferences(
//				Constant.SHOWIDENTITIES, 0);
//		boolean hasShowed = sharedPreferences.getBoolean(
//				Constant.FINISH_SHOWIDENTIFIES, false);
        Intent intent = null;
//		hasShowed=false;
        if (hasShowed) {// 展示过新特性直接显示主页
            intent = new Intent(StartUpActivity.this, HomeActivity.class);
        } else {// 没有展示过，进入展示新特性
            intent = new Intent(StartUpActivity.this, ShowNewIdentities.class);
        }
        startActivity(intent);
        StartUpActivity.this.overridePendingTransition(R.anim.alpha_in,
                R.anim.alpha_out);
        finish();
    }

    @Override
    protected void onDestroy() {
        if (adPicBitmap != null && !adPicBitmap.isRecycled()) {
            bgImageview.setImageBitmap(null);
            adPicBitmap.recycle();
        }
        super.onDestroy();
    }

    /**
     * 退出程序
     */
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void setDiskCache() {
        try {
            // 获取图片缓存路径
            File cacheDir = getDiskCacheDir(this, "AdImage");
            if (!cacheDir.exists()) {
                cacheDir.mkdirs();
            }
            // 创建DiskLruCache实例，初始化缓存数据
            mDiskCache = DiskLruCache.open(cacheDir,
                    Common.getAppVersion(this), 1, 2 * 1024 * 1024);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据传入的uniqueName获取硬盘缓存的路径地址。
     */
    public File getDiskCacheDir(Context context, String uniqueName) {
        String cachePath;
        if (Environment.MEDIA_MOUNTED.equals(Environment
                .getExternalStorageState())
                || !Environment.isExternalStorageRemovable()) {
            cachePath = context.getExternalCacheDir().getPath();
        } else {
            cachePath = context.getCacheDir().getPath();
        }
        return new File(cachePath + File.separator + uniqueName);
    }

    /**
     * 将缓存记录同步到journal文件中。
     */
    public void fluchCache() {
        if (mDiskCache != null) {
            try {
                mDiskCache.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 建立HTTP请求，并获取Bitmap对象。
     *
     * @param imageUrl 图片的URL地址
     * @return 解析后的Bitmap对象
     */
    private boolean downloadUrlToStream(String urlString,
                                        OutputStream outputStream) {
        HttpURLConnection urlConnection = null;
        BufferedOutputStream out = null;
        BufferedInputStream in = null;
        try {
            final URL url = new URL(urlString);
            urlConnection = (HttpURLConnection) url.openConnection();
            in = new BufferedInputStream(urlConnection.getInputStream(),
                    8 * 1024);
            out = new BufferedOutputStream(outputStream, 8 * 1024);
            int b;
            while ((b = in.read()) != -1) {
                out.write(b);
            }
            return true;
        } catch (final IOException e) {
            e.printStackTrace();
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (final IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

}
